﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Zxb.DayWork.Logic;
using System.ComponentModel;
using Zxb.DayWork.Core;

namespace Zxb.DayWork.Service
{
    public class DayWorkTimer
    {
        public static System.Timers.Timer timer = new System.Timers.Timer();

        internal static void initTimer()
        {
            timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
            timer.Interval = 1000 * 60 * 60 * 24;
            //timer.Enabled = true;
            timer_Elapsed(null, null);//启动立刻执行一次以便看效果
            while (DateTime.Now.Hour != 0) { Thread.Sleep(1000 * 60 * 30); }//半小时检查一次，如果到0点就跳出，开始执行
            timer.Start();//就是设置enabled
            timer_Elapsed(null, null);//timer.Start不会立刻执行，而是要等待一个周期
        }

        internal static void stopTimer()
        {
            timer.Elapsed -= timer_Elapsed;
            timer.Stop();
        }
        private static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            DoDayWork();
        }

        private static void DoDayWork()
        {
            Logger.InfoLog.Info("定时时刻到，调度开始");
            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += new DoWorkEventHandler(worker_DoWork);
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
            worker.RunWorkerAsync();
        }

        static void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Logger.InfoLog.Info("调度结束");
        }

        static void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                ReflectionAssistant.ReflectFromConfigFile();
            }
            catch (Exception ex)
            {
                Logger.InfoLog.Error("出错:" + ex.Message);
            }
        }
    }
}
